package com.lzxr.test.filter;

import com.lzxr.test.entity.UriView;
import com.lzxr.test.service.UriService;
import com.lzxr.test.service.impl.UriServiceImpl;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Optional;

public class MyFilter implements Filter {
    private UriService uriService = new UriServiceImpl();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 获取访问的 api
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String requestURI = req.getRequestURI();
        UriView uriView = new UriView();
        uriView.setUri(requestURI);

        // 将api访问记录下来
        uriService.save(uriView);

        // 进行登录验证，未登录跳转到登录页面
        String loginStatus = (String) Optional.ofNullable(req.getSession().getAttribute("isLogin")).orElse("false");
        if (!"true".equals(loginStatus)) {
            resp.sendRedirect("/index.jsp");
        }else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
